import { useTransitionSetting } from '@/hooks/setting/useTransitionSetting'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useUserStoreWithOut } from '@/store/modules/user'
import { unref } from 'vue'
import router from '..'

const userStore = useUserStoreWithOut()
const appStore = useAppStoreWithOut()
const { getOpenPageLoading } = useTransitionSetting()
router.beforeEach(async (to: any) => {
  if (!userStore.getToken) {
    return true
  }
  if (to.meta.loaded) {
    return true
  }

  if (unref(getOpenPageLoading)) {
    appStore.setPageLoadingAction(true)
    return true
  }

  return true
})
router.afterEach(async () => {
  if (unref(getOpenPageLoading)) {
    // TODO Looking for a better way
    // The timer simulates the loading time to prevent flashing too fast,
    setTimeout(() => {
      appStore.setPageLoading(false)
    }, 220)
  }
  return true
})
